<?php

/**
 * CodeRS - Atviras kodas Lietuvai
 * Copyright (C) 2007 CodeRS www.coders.lt info@coders.lt
 * MightMedia TVS
 * bendras.php - nurodome kokius veiksmus atlikti prieš puslapiui užsikraunant
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 * 
 * Ši programa yra laisva. Jūs galite ją platinti ir/arba modifikuoti
 * remdamiesi Free Software Foundation paskelbtomis GNU Bendrosios
 * Viešosios licencijos sąlygomis: 2 licencijos versija, arba (savo
 * nuožiūra) bet kuria vėlesne versija.
 * 
 * Ši programa platinama su viltimi, kad ji bus naudinga, bet BE JOKIOS
 * GARANTIJOS; be jokios numanomos PERKAMUMO ar TINKAMUMO KONKRETIEMS
 * TIKSLAMS garantijos. Žiūrėkite GNU Bendrąją Viešąją licenciją norėdami
 * sužinoti smulkmenas.
 * 
 * Jūs turėjote kartu su šia programa gauti ir GNU Bendrosios Viešosios
 * licencijos kopija; jei ne - rašykite Free Software Foundation, Inc., 59
 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**/

// Klaidų rodymas
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');

// Surandam config.php
$home_dir = "";
while (!file_exists($home_dir."variklis/funkcijos.php")) { $home_dir .= "../"; }
define("HOME_DIR", $home_dir);	//nustatom root direktorija "../"

//Tikrinam ar įdiegta TVS
if (!file_exists(HOME_DIR."variklis/config.php")) { header("Location: setup.php"); exit; } //Jei nėra failo, vykdom TVS diegimą

/*
// Apsauga nuo GET: XSS ir MySQL injections
$QUERY_STRING = $_SERVER['QUERY_STRING'];
if (!empty($QUERY_STRING)) {
	if (preg_match("/SERVER|http|<|>|%3c|%3e|'|\"|SELECT|UNION|UPDATE|INSERT/i", $QUERY_STRING)) {
		$ip = (isset($_SERVER["HTTP_CLIENT_IP"]) && !empty($_SERVER["HTTP_CLIENT_IP"]) ? $_SERVER["HTTP_CLIENT_IP"] : 'N/A');
		$forwarded = (isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && !empty($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : 'N/A');
		$remoteaddress = (isset($_SERVER["REMOTE_ADDR"]) && !empty($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : 'N/A');

		$message = "Failas: ".$_SERVER['PHP_SELF']."\n Užklausa: ".$QUERY_STRING."\n Tipas: ".$_SERVER['REQUEST_METHOD']."\n IP: (ip-forw-RA):- ".$ip." - ".$forwarded." - ".$remoteaddress."\n";
		ban(str_replace("\n",'',$message));
		//if (!@mail((isset($admin_email) ? $admin_email : "projektas@gmail.com"), "BOMŽAS - ".date('Y-m-d'), $message, "From: host@".$_SERVER['SERVER_NAME'])) echo nl2br($message);

		die("<hr /><h1>Bomžams ne!</h1>");
	}
}
*/
//
// Unset any variables instantiated as a result of register_globals being enabled
//
$register_globals = @ini_get('register_globals');
if ($register_globals === "" || $register_globals === "0" || strtolower($register_globals) === "off") {
	//nieko nedarom
} else {
	// Prevent script.php?GLOBALS[foo]=bar
	if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS']))
		exit("<hr /><h1>Bomžams ne!</h1>");
	
	// Variables that shouldn't be unset
	$no_unset = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');

	// Remove elements in $GLOBALS that are present in any of the superglobals
	$input = array_merge($_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());
	foreach ($input as $k => $v) {
		if (!in_array($k, $no_unset) && isset($GLOBALS[$k])) {
			unset($GLOBALS[$k]);
			unset($GLOBALS[$k]);	// Double unset to circumvent the zend_hash_del_key_or_index hole in PHP <4.4.3 and <5.1.4
		}
	}
}

// Turn off magic_quotes_runtime
set_magic_quotes_runtime(0);

// Strip slashes from GET/POST/COOKIE (if magic_quotes_gpc is enabled)
if (get_magic_quotes_gpc()) {
	function stripslashes_array($array) {
		return is_array($array) ? array_map('stripslashes_array', $array) : stripslashes($array);
	}

	$_GET = stripslashes_array($_GET);
	$_POST = stripslashes_array($_POST);
	$_COOKIE = stripslashes_array($_COOKIE);
}

if (isset($_GET['q']) && !empty($_GET['q'])) {
	if(!preg_match("/^[0-9a-žA-Ž_,;\/]+$/", $_GET['q'])) {
		die("<hr /><h1>Bomžams ne!</h1>");
	}
}
if(isset($_GET) && count($_GET) > 1) {
	die("<hr /><h1>Bomžams ne!</h1>");
}


// IP baninimas ant serverio
function ban($message, $ip='', $status='deny') {
	if (empty($ip)) $ip = $_SERVER['REMOTE_ADDR'];
	if ($ip != '127.0.0.1') {
		$file = '.htaccess';
		if (file_exists($file) && is_writable($file)) {
			$fh = fopen($file,'a');
			fwrite($fh,"\n#".$message."\n".$status.' from '.$ip."\n");
			fclose($fh);
		}
	}
}
//
// Cache class
//
require HOME_DIR."variklis/class/cache.php";
$cache = &new cache;

//
// DB Prisijungimas
//
require (HOME_DIR."variklis/config.php");
require (HOME_DIR."variklis/class/mysql.php");
$db = new sql($host, $user, $pass, $dbo);
unset($host,$user,$pass,$dbo);

$db->uzklausa("SET NAMES utf8");	//Jeigu serveryje default koduote nenustatyta arba ji ne utf-8 ir sitos eilutės nebus nerodys LT raidziu
$conf = $db->masyvas($db->uzklausa("SELECT SQL_CACHE * FROM `".LENTELES_PRIESAGA."nustatymai` LIMIT 1"));//Bendri nustatymai
// TODO: Ateityje galetu buti cache
/*
CREATE TABLE `nustatymai` (
  `name` varchar(48) NOT NULL default '',
  `value` longtext NOT NULL,
  PRIMARY KEY  (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

$result = $db->uzklausa("SELECT SQL_CACHE * FROM `".LENTELES_PRIESAGA."nustatymai`");
while ($row = $db->masyvas($result)) {
	$conf[$row['name']] = unserialize($row['value']);
}
*/
//
//Nustom sistemos kintamuosius
//
if (isset($_SERVER)) {
	if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	elseif (isset($_SERVER["HTTP_CLIENT_IP"]))
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	else
		$ip = $_SERVER["REMOTE_ADDR"];
} else {
	if (getenv('HTTP_X_FORWARDED_FOR'))
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	elseif (getenv('HTTP_CLIENT_IP'))
		$ip = getenv('HTTP_CLIENT_IP');
	else
		$ip = getenv('REMOTE_ADDR');
}
define("IP", htmlspecialchars($ip, ENT_QUOTES, 'UTF-8')); unset($ip);
define("DOMAIN", "");
define("PSL", (isset($_GET['q'])) ? htmlspecialchars($_GET['q'], ENT_QUOTES, 'UTF-8') : '');
define("NARSYKLE", (!empty($_SERVER['HTTP_USER_AGENT'])) ? htmlspecialchars($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8') : 'N/A');
define("QUOTES", get_magic_quotes_gpc());

define("T_USERS", LENTELES_PRIESAGA."users");
define("T_SESSIONS", LENTELES_PRIESAGA."sessions");
define("T_SESSIONS_KEYS", LENTELES_PRIESAGA."sessions_keys");
define("T_SAUKYKLA", LENTELES_PRIESAGA."saukykla");
define("T_MENIU", LENTELES_PRIESAGA."meniu");

//
// Sesijos
//
require(HOME_DIR."variklis/class/session.php");
$ses = new session;

$loginERROR = "";
if (isset($_GET['atsijungti'])) $ses->atsijungti();
if (isset($_POST['prisijungimas'])) $ses->prisijungti();

$ses->identifikuoti();
// Jeigu kartais netycia nebutu nusistates PRISIJUNGES:
if (!defined('PRISIJUNGES')) {
	define("PRISIJUNGES", false);
}

$ses->isvalyti_mysql();

//Vartotojo duomenys
define("USER_ID", (PRISIJUNGES) ? $ses->user_data['user_id'] : 1);
define("USER_RIGHTS", (PRISIJUNGES) ? $ses->user_data['teises'] : '');
define("LYGIS", (PRISIJUNGES) ? $ses->user_data['lygis'] : 1);
define("MOD", (PRISIJUNGES && $ses->user_data['lygis'] >= 20) ? true : false);
define("ADMIN", (PRISIJUNGES && $ses->user_data['lygis'] >= 30) ? true : false);
define("S_ADMIN", (PRISIJUNGES && $ses->user_data['lygis'] == 33) ? true : false);

//Teisių tikrinimas
function CheckRights($right) {
	if (S_ADMIN || (ADMIN && in_array($right, explode(".", USER_RIGHTS))))
		return true;
	else
		return false;
}

//Įkeliam pagrindines funkcijas
require (HOME_DIR."lang/lt.php");

//Įkeliam pagrindines funkcijas
require (HOME_DIR."variklis/funkcijos.php");

//Įkeliam stiliaus funkcijas
if (file_exists(HOME_DIR."templates/".$conf['template']."/sfunkcijos.php"))
	require (HOME_DIR."templates/".$conf['template']."/sfunkcijos.php");
else
	die("<p><b>Error:</b> Nėra šablono stiliaus funkcijų failo (sfunkcijos.php).</p>");

//
// Modules
//
$modules_sql = $db->uzklausa("SELECT SQL_CACHE * FROM `".LENTELES_PRIESAGA."modules` WHERE `status`=1");// AND (`boot`=1 OR `name`='".$URL_module."')
$boot_modules = array();
$url_modules_list = array();
while($row = $db->masyvas($modules_sql)) {
	if($row['boot'] == 1) $boot_modules[] = $row;
	else $url_modules_list[] = $row;
}
$db->free_result($modules_sql);

//
// $_GET['q'] - Friendly URLs
//
if(isset($_GET['q']) && !empty($_GET['q'])) {
	$URL_real = $_GET['q'];//Jeigu yra kalbos nustatymas jis nerodomas

	if(preg_match("/^\?+/", $URL_real)) {
		list($URL_static, $URL_additional) = split("?", $URL_real, 2);
	} //else {
	$URL_additional = "";
	if(preg_match("/^\/+/", $URL_real))
		$URL_array = explode("/", $URL_real);
	else
		$URL_array[0] = $URL_real;

	$urls_num = count($URL_array);
	if($urls_num > 10) {
		die("Error/Klaida: negali būti tiek daug per \$_GET perduodamų kintamųjų! Too much \"folders\" in url.");
	}

	if($conf['multilang'] == 1) {
		if(!isset($URL_array[0]{2}) && isset($URL_array[0]{1})) {//Ar tinkamas ilgis $lang nustatymui
			$url_module = array_search($conf['multilang_list'], $URL_array[0]);
			if ($url_module !== false) {
				// TODO: $lang BŪTINA nustatyti sesijoje atsiminimui
				$lang = array_shift($URL_array); //Paimamas pirmasis masyvo elementas
				//array_unshift($URL_array, "apple");
				$URL_real = str_replace($lang.'/', '', $URL_real_without_lang);//Iš URL išimamas $lang nustatymas, jo mums daugiau nebeprireiks URL adrese
			}
		}
	}

	// START - Bando rasti additional kintamuosius
	$pries_paskutinis = count($URL_array) -1;
	if(preg_match("/(,|;)+/", $URL_array[$pries_paskutinis])) {
		$URL_additional = (string) array_pop($URL_array);//Paimamas paskutinis masyvo elementas
		$URL_additional = (array) UrlToArray($URL_additional);
	}
	unset($pries_paskutinis);
	// END - Bando rasti additional kintamuosius

	// START - Url alias module
	$url_sql = $db->uzklausa("SELECT * FROM `".LENTELES_PRIESAGA."url_alias` WHERE `dst`='".$db->fix($URL_real)."'");
	if($db->num_rows($url_sql) == 1) {
		$URL_alias = $db->masyvas($url_sql);
		unset($URL_array);
		$URL_array = explode("/", $URL_alias['src']);
		unset($URL_alias);
	}
	$db->free_result($url_sql);
	// END - Url alias module

	$URL_module = array_shift($URL_array); //Paimamas pirmasis masyvo elementas
} else {
	$URL_module = $conf['module_default'];//
	if($conf['multilang'] == 1)
		$lang = $conf['lang_default'];// TODO: sesijos lang turetu buti
	$URL = array();
	$URL_real = "";
}


//
// Include/Įkelti boot modules (kurie privalomi visuose psl.)
//
foreach ($boot_modules as $value) {
	include($value);
}
$url_module = array_search($URL_module, $url_modules_list);
unset($URL_module);
if ($url_module === false) {
	$url_module = '';
	//die("Tokio modulio nėra!");
} else {
	$url_module = $url_modules_list[$url_module];
}

//
// Template engine class
//
require HOME_DIR."variklis/class/tpl.php";
$tpl = &new template("./templates/".$conf['template']."/tpl/");
$tpl_common_vars = array();
/*
$tpl->setBlockVars('c', array(
'AUTHOR' => stripslashes($author),
'KOMENTARAS' => stripslashes($komentaras))
);
*/

?>
